﻿using System;
using System.Collections.Generic;
using System.Web;


namespace CCPSIP.vCard
{
    /// <summary>CCPSIP_044：vCard 名片交換待下載清單 API</summary>
    /// idHeader = 裝置 UUID 前八碼。
    /// checkcode = 裝置限時驗證碼。

    public class vcf_download_list : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";


            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }


                //【02】取得待下載的vCard清單
                //
                List<Dictionary<string, string>> dictList = new List<Dictionary<string, string>>();
                vCardExchInfo[] exchArray = OracleKitVCard.getToDownloadList(userInfo.SIP_Num);

                for (int i = 0; i < exchArray.Length; i++)
                {
                    vCardExchInfo vInfo = exchArray[i];
                    Dictionary<string, string> newDict = new Dictionary<string, string>();
                    newDict["vCardExchID"] = Convert.ToString(vInfo.vCardExchID);
                    newDict["ReplyTime"] = string.Format("{0:yyyy/MM/dd HH:mm:ss}", vInfo.ReplyTime);
                    newDict["InitTime"] = string.Format("{0:yyyy/MM/dd HH:mm:ss}", vInfo.InitTime);
                    newDict["Scanner"] = vInfo.Scanner;
                    newDict["Replier"] = vInfo.Replier;

                    if (userInfo.SIP_Num == vInfo.Scanner)
                        newDict["vCardKey"] = string.Format(@"{0}_{1:yyyyMMdd_HHmmss}", vInfo.Replier, vInfo.ReplyTime);
                    else
                        newDict["vCardKey"] = string.Format(@"{0}_{1:yyyyMMdd_HHmmss}", vInfo.Scanner, vInfo.InitTime);

                    dictList.Add(newDict);
                }


                //【03】取得待下載的群組交換vCard清單
                //
                Dictionary<string, string>[] vCardDicts = OracleKitVCardGE.getToDownloadList(userInfo.SIP_Num);
                foreach (Dictionary<string, string> dict in vCardDicts)
                {
                    Dictionary<string, string> newDict = new Dictionary<string, string>();

                    newDict["vCardExchID"] = string.Format("{1}{0}{2}{0}{3}", vcf_download.kVGESeparator,
                      vcf_download.kVGEPrefix, dict["VGEID"], dict["vCardOwner"]);
                    newDict["ReplyTime"] = dict["UpdateTime"];
                    newDict["InitTime"] = dict["InitTime"];
                    newDict["Scanner"] = "";
                    newDict["Replier"] = dict["vCardOwner"];
                    newDict["vCardKey"] = dict["vCardKey"];
                    dictList.Add(newDict);
                }


                //【99】以JSON格式回傳
                //
                resp.ContentType = "application/json";
                resp.Charset = null;
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = fastJSON.JSON.Instance.ToJSON(dictList);
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
